<template>
    <el-form
        class="sign-form"
        ref="loginRef"
        :model="loginForm"
        :rules="loginRuleForm"
    >
        <el-form-item class="sign-form-item" prop="user_name">
            <el-input
                class="sign-form-input"
                placeholder="用户名"
                v-model="loginForm.user_name"
            ></el-input>
        </el-form-item>
        <el-form-item class="sign-form-item" prop="pwd">
            <el-input
                class="sign-form-input"
                placeholder="密码"
                v-model="loginForm.pwd"
            ></el-input>
        </el-form-item>
    </el-form>
    <div class="login-options">
        <el-checkbox v-model="loginForm.keep">记住我</el-checkbox>
        <RouterLink class="link" to="/reset-pwd">忘记密码</RouterLink>
    </div>
    <div>
        <el-button
            class="submit"
            type="primary"
            :loading="loading"
            @click="submit"
        >
            登 录
        </el-button>
    </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import type { LoginForm } from '@/types'
import { login } from '@/api/users'
import { LocalStorage } from '@/utils/use-storage'

const router = useRouter()

const loginForm = ref<LoginForm>({
    user_name: 'wangwang',
    pwd: '123456',
    keep: true,
})

const loginRef = ref<FormInstance>()

const loginRuleForm = ref<FormRules<LoginForm>>({
    user_name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    pwd: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})

const loading = ref<boolean>(false)

const submit = () => {
    loginRef.value?.validate(async (valid) => {
        if (valid) {
            loading.value = true
            const res = await login(loginForm.value)
            if (res.success) {
                loading.value = false
                const { accessToken, refreshToken } = res.data
                if (accessToken) {
                    LocalStorage.set('accessToken', accessToken)
                }
                if (refreshToken) {
                    LocalStorage.set('refreshToken', refreshToken)
                }
                
                router.push('/')
            }
        }
    })
}
</script>

<style lang="less" scoped>
@import url('./sign-form.less');
.login-options {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .link {
        font-size: var(--font-size-medium);
    }
}
</style>
